﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AnalysisSystem
{
    class RelativeTimeMethod
    {
        /// <summary>
        /// 加入相对时间列的方法
        /// </summary>
        /// <param name="wellName">包含选取的井名</param>
        /// <param name="dataSource">包含源数据的表</param>
        /// <returns></returns>
        public static DataTable RelativeTime(List<string> wellName, in DataTable dataSource)
        {
            DataTable returnTable = new DataTable();
            returnTable = dataSource.Clone();
            returnTable.Columns.Add("相对时间");
            returnTable.Columns["相对时间"].DataType = typeof(DateTime);
            for (int i = 0; i < wellName.Count; i++)
            {
                DataTable table = SelectTable(wellName[i], in dataSource);
                AddData(ref returnTable, ref table);
            }
            return returnTable;
        }
        /// <summary>
        /// 根据井名选择表
        /// </summary>
        /// <param name="wellName">井名</param>
        /// <param name="dataSource">包含源数据表</param>
        /// <returns></returns>
        private static DataTable SelectTable(string wellName, in DataTable dataSource)
        {
            var table = from p in dataSource.AsEnumerable()
                        where p.Field<string>("井号").Equals(wellName)
                        orderby p.Field<DateTime>("日期")
                        select p;
            return table.CopyToDataTable<DataRow>();
        }
        /// <summary>
        /// 加入相对时间的列数据
        /// </summary>
        /// <param name="retTable">返回的数据表</param>
        /// <param name="table">筛选出的数据表</param>
        private static void AddData(ref DataTable retTable, ref DataTable table)
        {
            DateTime start = Convert.ToDateTime(table.Rows[0]["日期"]);
            DateTime end = Convert.ToDateTime(table.Rows[table.Rows.Count - 1]["日期"]);
            table.Columns.Add("相对时间");            
            for(int i=0; i<table.Rows.Count; i++)
            {
                DateTime initial = new DateTime();
                DateTime now = Convert.ToDateTime(table.Rows[i]["日期"]);
                TimeSpan span = now - start;
                initial += span;
                table.Rows[i]["相对时间"] = initial;                                
                retTable.Rows.Add(table.Rows[i].ItemArray);                
            }
        }
    }
}
